package com.dianrui.operation.update;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat.Builder;


import com.dianrui.operation.R;
import com.dianrui.operation.util.FileUtils;
import com.dianrui.operation.util.MyUtil;
import com.dianrui.operation.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 下载APK的服务
 */

public class DownloadService extends IntentService {
    private static final int BUFFER_SIZE = 10 * 1024; // 8k ~ 32K
    private static final String TAG = "DownloadService";
    private NotificationManager mNotifyManager;
    private Builder mBuilder;

    public static final String ACTION_UPDATE = "com.dianrui.operation.service.action.UPDATE_APK";

    public static final String EXTRA_APK_PATH = "com.dianrui.operation.service.extra.APK_PATH";


    public final String SAVE_FILE = "operations/Download";

    private String apkPath;

    private int hintCount = 0;

    public DownloadService() {
        super("DownloadService");
    }


    public void startActionUpdate(Context context, String apkPath) {
        Intent intent = new Intent(context, DownloadService.class);
        intent.setAction(ACTION_UPDATE);
        intent.putExtra(EXTRA_APK_PATH, apkPath);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_UPDATE.equals(action)) {
                apkPath = intent.getStringExtra(EXTRA_APK_PATH);
            }
        }
        if (StringUtils.isEmpty(apkPath)) {
            return;
        }

        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new Builder(this);

        String appName = getString(getApplicationInfo().labelRes);
        int icon = getApplicationInfo().icon;

        mBuilder.setContentTitle(appName).setSmallIcon(icon);

        InputStream in = null;
        FileOutputStream out = null;
        try {
            URL url = new URL(apkPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.setReadTimeout(10 * 1000);
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Charset", "UTF-8");
            urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

            urlConnection.connect();
            long bytetotal = urlConnection.getContentLength();
            long bytesum = 0;
            int byteread = 0;
            in = urlConnection.getInputStream();

            String apkName = apkPath.substring(apkPath.lastIndexOf("/") + 1, apkPath.length());

            //File apkFile = FileUtils.getSaveFile(SAVE_FILE, apkName);
            File apkFile = new File(Environment.getExternalStorageDirectory(), "/download/" + System.currentTimeMillis() +"/"+ apkName);
            if (!apkFile.getParentFile().exists()) {
                apkFile.getParentFile().mkdirs();
            }
            //File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + BaseApplication.currentTime + ".jpg");

            out = new FileOutputStream(apkFile);
            byte[] buffer = new byte[BUFFER_SIZE];

            int oldProgress = 0;

            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread);

                int progress = (int) (bytesum * 100L / bytetotal);
                // 如果进度与之前进度相等，则不更新，如果更新太频繁，否则会造成界面卡顿
                if (progress != oldProgress) {
                    updateProgress(progress);
                }
                oldProgress = progress;
            }
            // 下载完成
            mBuilder.setContentText(getString(R.string.download_success)).setProgress(100, progress, false);

            setInstallApk(apkFile);

            Intent installAPKIntent = new Intent(Intent.ACTION_VIEW);
            //如果没有设置SDCard写权限，或者没有sdcard,apk文件保存在内存中，需要授予权限才能安装
            String[] command = {"chmod", "777", apkFile.toString()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();

            installAPKIntent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, installAPKIntent, PendingIntent.FLAG_UPDATE_CURRENT);

            mBuilder.setContentIntent(pendingIntent);
            Notification noti = mBuilder.build();
            noti.flags = Notification.FLAG_AUTO_CANCEL;
            mNotifyManager.notify(0, noti);

        } catch (Exception e) {
            if (hintCount == 0) {
                hintCount++;

                progress = -100;
                downloadException = e.toString();

                FileUtils.clearFileOrFiles(FileUtils.getSavePath(SAVE_FILE));
            }


        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 下载进度
     */
    private void updateProgress(int progress) {
        this.progress = progress;

        //"正在下载:" + progress + "%"
        mBuilder.setContentText(this.getString(R.string.download_progress, progress)).setProgress(100, progress, true);
        //setContentInent如果不设置在4.0+上没有问题，在4.0以下会报异常
        PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(0, mBuilder.build());
    }


    /**
     * 下载完成
     */
    private void setInstallApk(File file) {
        if (file.exists() && file.length() > 0) {
            MyUtil.installApkNew(this, file);
        }
    }


    /**
     * 返回一个Binder对象
     */
    int progress;
    String downloadException;

    private final IBinder binder = new LocalBinder();

    public class LocalBinder extends Binder {

        public DownloadService getService() {
            return DownloadService.this;
        }

        /**
         * 获取进度
         *
         */
        public int getProgress() {
            return progress;
        }

        public String getDownloadExceptionInfo() {
            return downloadException;
        }

        public void setDownloadEnd() {
            progress = 0;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }



}
